<?php
require_once("serverFunctions.php");
require_once("AnkaraPharmacyParser.php");
require_once("IstanbulPharmacyParser.php");
require_once("IzmirPharmacyParser.php");
error_reporting(E_ERROR | E_PARSE);

ini_set("display_errors", 1);
date_default_timezone_set("Europe/Minsk"); //proper timezone for Turkey
$db = getMysqlObject();

$nOfDaysToFetch=1; //excluding yesterday

$today = date('Y-m-d');
echo $today;
$sql = "select * from Counties where date = '$today' ";
$result = $db->query($sql);
$numCount = $db->numRows($result);
echo "pharmacy count:" . $numCount;
if ($numCount > 190) {
   exit;
}


if ($db->query("truncate Counties")) {;  //clear db
   echo "truncate works properly";
}

$sqlInsertAnkara  = "INSERT INTO `Counties` (`ID`, `parentId`, `Name`, `pharmacyAddress`, `pharmacyPhone`, `isPharmacy`, `lattitude`, `longitude`, `pharmacyURL`, `date`) VALUES (1, '', 'ANKARA', '', '', 0, 39.92,32.82, '', '')";
$db->query($sqlInsertAnkara);

$sqlInsertIstanbul  = "INSERT INTO `Counties` (`ID`, `parentId`, `Name`, `pharmacyAddress`, `pharmacyPhone`, `isPharmacy`, `lattitude`, `longitude`, `pharmacyURL`, `date`) VALUES (2, '', 'İSTANBUL', '', '', 0, 0, 0, '', '')";
$db->query($sqlInsertIstanbul);

$sqlInsertIzmir  = "INSERT INTO `Counties` (`ID`, `parentId`, `Name`, `pharmacyAddress`, `pharmacyPhone`, `isPharmacy`, `lattitude`, `longitude`, `pharmacyURL`, `date`) VALUES (3, '', 'İZMİR', '', '', 0, 0, 0, '', '')";
$db->query($sqlInsertIzmir);

$sqlFirstPart = "INSERT INTO Counties (`parentId`, `Name`, `pharmacyAddress`, `pharmacyPhone`, `isPharmacy`, `lattitude`, `longitude`, `pharmacyURL`, `date`) VALUES ";

$sqlDatas = array();

/*Fetch Istanbul Pharmacies*/
$istanbulCountiesCount=39;
//First, fetch counties from the website 
$istanbulPharmacyURL = "http://www.istanbulsaglik.gov.tr/w/nobet/liste.asp?"; 
$date = date('d.m.Y',mktime(0,0,0,date('m'), date('d'), date('Y')));
$str = file_get_contents($istanbulPharmacyURL."lc=0&gun=".$date);
$dom = new DOMDocument('1.0', 'iso-8859-9');
$dom->loadHTML($str);
$domContainerPanel = $dom->getElementById("AutoNumber8")->getElementsByTagName("tr");
$istanbulCounties = array();

for($j=0; $j<$istanbulCountiesCount; $j++)
{
	$county = $domContainerPanel->item(0)->childNodes->item(0)->childNodes->item(3+ 4*($j))->nodeValue;
	$sqlInsertIstanbulCounty  = "INSERT INTO `Counties` (`ID`, `parentId`, `Name`, `pharmacyAddress`, `pharmacyPhone`, `isPharmacy`, `lattitude`, `longitude`, `pharmacyURL`, `date`) VALUES ('', '2', '".$county."', '', '', 0, 0, 0, '', '')";
	$db->query($sqlInsertIstanbulCounty);
}

$sqlDatas = array();
//start with yesterday
$dom = new DOMDocument('1.0', 'iso-8859-9');
for($dayOffset=-1; $dayOffset<$nOfDaysToFetch; $dayOffset++)
{
	//get the javascript function parameter for all pharmacies at the specified date and store in array.
	$countyIndex=4; //start index of Istanbul Counties
	$requestParams = array();
	$date = date('d.m.Y',mktime(0,0,0,date('m'), date('d') + $dayOffset, date('Y')));
	$str = file_get_contents($istanbulPharmacyURL."lc=0&gun=".$date);
	$dom->loadHTML($str);
	$domContainerPanel = $dom->getElementById("AutoNumber8")->getElementsByTagName("tr");
	for($j=0; $j<$istanbulCountiesCount; $j++) {
		$par = strbet($domContainerPanel->item(0)->childNodes->item(0)->childNodes->item(3+ 4*($j))->getAttribute('href'),"'","'");	
		//then call the javascript function with the corresponding parameter
		$str = file_get_contents("http://ismgis.istanbulsaglik.gov.tr/eczane/GetNobetciEczaneler.aspx".$par);
		$pharmacyParser = new IstanbulPharmacyParser();
		$pharmacyList = $pharmacyParser->parsePharmacies($str);		
		$length = count($pharmacyList);
		$date = date('y-m-d',mktime(0,0,0,date('m'), date('d')+$dayOffset, date('Y')));
		$pharmacyParentId= $countyIndex;
		for ($i = 0; $i < $length; $i++)
		{
		    $temp = " ('".htmlspecialchars($pharmacyParentId,ENT_QUOTES)."','". htmlspecialchars($pharmacyList[$i]->getName(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getAddress(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getPhone(),ENT_QUOTES)."', 1, '".htmlspecialchars($pharmacyList[$i]->getLatitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getLongitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getURL(),ENT_QUOTES)."', '".htmlspecialchars($date,ENT_QUOTES)."')";	
			array_push($sqlDatas, $temp);
		}
		$countyIndex++;
	}
}

$sqlSecondPart = implode(",", $sqlDatas);
$sqlIstanbulPharmacies = $sqlFirstPart . $sqlSecondPart;
/*insert Istanbul Pharmacies into db*/
if ($db->query($sqlIstanbulPharmacies))
{
   echo "<br>istanbul pharmacies are inserted";
}
else {
   echo "<br>problem in inserting istanbul pharmacies";
}
/*Fetch Istanbul Pharmacies ends*/


/*Fetch Ankara Pharmacies*/
$initialRequestNumber=4278;
$initialDate = '2011-09-18';
$today = date('Y-m-d',mktime(0,0,0,date('m'), date('d'), date('Y')));
$daysDifference = (int)((strtotime(date($today))-strtotime($initialDate))/86400);
$requestNumber = $initialRequestNumber+$daysDifference;
$sqlDatas = array();	
$url = 'http://www.aeo.org.tr/Sayfalar/Nobetci.aspx';

$rawdata = file_get_contents($url);

$dom = new DOMDocument('1.0', 'iso-8859-9');
$dom->loadHTML($rawdata); // burada loadHtmlFile kullanilabilir.
$viewState = $dom->getElementById("__VIEWSTATE")->getAttribute("value");
$eventValidation = $dom->getElementById("__EVENTVALIDATION")->getAttribute("value");

//start with yesterday
for($dayOffset=-1; $dayOffset<$nOfDaysToFetch; $dayOffset++)
{
	$fields = array(
	            '__EVENTTARGET'=>urlencode('ctl00$Middle$CalendarNobetTarihi'),
	            '__EVENTARGUMENT'=>urlencode($requestNumber+$dayOffset),
				'__VIEWSTATE'=>urlencode($viewState),
				'__EVENTVALIDATION'=>urlencode($eventValidation),					
	);
	
	
	$fields_string = "";
	//url-ify the data for the POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	
	//open connection
	$ch = curl_init();
	
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE); 
	
	//execute post
	$result = curl_exec($ch);
	curl_close($ch);

	
	$pharmacyParser = new AnkaraPharmacyParser();
	$pharmacyList = $pharmacyParser->parsePharmacies($result);
	$length = count($pharmacyList);
	$parentId = 1;  // girilen ankara ilinin id si last insert id

	$date = date('y-m-d',mktime(0,0,0,date('m'), date('d')+$dayOffset, date('Y')));
	
	for ($i = 0; $i < $length; $i++)
	{
	    $temp = " ('".htmlspecialchars($parentId,ENT_QUOTES)."','".htmlspecialchars($pharmacyList[$i]->getName(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getAddress(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getPhone(),ENT_QUOTES)."', '1', '".htmlspecialchars($pharmacyList[$i]->getLatitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getLongitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getURL(),ENT_QUOTES)."', '".htmlspecialchars($date,ENT_QUOTES)."')";	
		array_push($sqlDatas, $temp);
	}

}
$sqlSecondPart = implode(",", $sqlDatas);

$sqlAnkaraPharmacies = $sqlFirstPart . $sqlSecondPart;

/*insert Ankara Pharmacies into db*/
if ($db->query($sqlAnkaraPharmacies)) {
   echo "<br>ankara pharmacies are inserted";
}
else {
   echo "<br>problem in inserting ankara pharmacies";
}
/*Fetch Ankara Pharmacies ends*/


/*Fetch Izmir Pharmacies*/
$sqlDatas = array();	
$url = "http://www.izmireczaciodasi.org.tr/NobetciEczane.asp";

//start with yesterday
for($dayOffset=-1; $dayOffset<$nOfDaysToFetch; $dayOffset++)
{
	$date = date('d.m.Y',mktime(0,0,0,date('m'), date('d')+$dayOffset, date('Y')));
	
	$fields = array(
				'tarih'=>urlencode($date),
				'submit'=>urlencode("Listele")				
	);
	
	
	$fields_string = "";
	//url-ify the data for the POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	
	//open connection
	$ch = curl_init();
	
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE); 
	
	//execute post
	$result = curl_exec($ch);
	curl_close($ch);
	
	$pharmacyParser = new IzmirPharmacyParser();
	$pharmacyList = $pharmacyParser->parsePharmacies($result);
	$length = count($pharmacyList);
	$parentId = 3;  // girilen izmir ilinin id si parentId
	
	$date = date('y-m-d',mktime(0,0,0,date('m'), date('d')+$dayOffset, date('Y')));
	
	for ($i = 0; $i < $length; $i++)
	{
	    $temp = " ('".htmlspecialchars($parentId,ENT_QUOTES)."','".htmlspecialchars($pharmacyList[$i]->getName(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getAddress(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getPhone(),ENT_QUOTES)."', '1', '".htmlspecialchars($pharmacyList[$i]->getLatitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getLongitude(),ENT_QUOTES)."', '".htmlspecialchars($pharmacyList[$i]->getURL(),ENT_QUOTES)."', '".htmlspecialchars($date,ENT_QUOTES)."')";	
		array_push($sqlDatas, $temp);
	}
}
$sqlSecondPart = implode(",", $sqlDatas);
$sqlIzmirPharmacies = $sqlFirstPart . $sqlSecondPart;
/*insert Izmir Pharmacies into db*/
if ($db->query($sqlIzmirPharmacies)) {
    echo "<br>izmir pharmacies are inserted";
}
else {
    echo "<br>problem in inserting izmir pharmacies";
}
/*Fetch Izmir Pharmacies ends*/

//This function is used to fetch substring between specified deliminiters
function strbet($inputStr, $delimeterLeft, $delimeterRight, $debug=false) { 
    $posLeft=strpos($inputStr, $delimeterLeft); 
    if ( $posLeft===false ) { 
        if ( $debug ) { 
            echo "Warning: left delimiter '{$delimeterLeft}' not found"; 
        } 
        return false; 
    } 
    $posLeft+=strlen($delimeterLeft); 
    $posRight=strpos($inputStr, $delimeterRight, $posLeft); 
    if ( $posRight===false ) { 
        if ( $debug ) { 
            echo "Warning: right delimiter '{$delimeterRight}' not found"; 
        } 
        return false; 
    } 
    return substr($inputStr, $posLeft, $posRight-$posLeft); 
} 

?>